
package com.ml.mall.security;

import com.ml.mall.bean.SpringContextHolder;
import com.ml.mall.entity.sys.ShiroUser;
import com.ml.mall.service.sys.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;


/**
 * @description: 权限token认证
 * @author kyyang
 * @date 2020/12/28 20:15
 * @version 1.0
 */

@Service
@Slf4j
public class ApiRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService userService;
    @Autowired
    private ShiroFactroy shiroFactroy;



    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


/**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Long userId = JwtUtil.getUserId(principals.toString());

        ShiroUser user = shiroFactroy.shiroUser(userService.getById(userId));
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(user.getRoleCode());
        Set<String> permission = user.getPermissions();
        //资源的权限标识采用menu中的code和url，建议统一以url为准
        simpleAuthorizationInfo.addStringPermissions(permission);
       // simpleAuthorizationInfo.addStringPermissions(user.getUrls());
        return simpleAuthorizationInfo;
    }


    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        Long userId = JwtUtil.getUserId(token);
        if (userId == null) {
            throw new AuthenticationException("Login has expired！");
        }
        SysUserService userService = SpringContextHolder.getBean(SysUserService.class);

        boolean b = userService.refreshTokenIsValid(token);
        if(!b){
           throw new AuthenticationException("Login has expired！");
        }

        ShiroUser userBean = ShiroFactroy.me().shiroUser(userService.getById(userId));
        if (userBean == null) {
            throw new AuthenticationException("The user does not exist.！");
        }

        if (!JwtUtil.verify(token, userBean.getAcc(), userBean.getPwd())) {
            throw new AuthenticationException("User name or password error！");
        }

        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }
}

